package com.ph.permission.api.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.bingoohuang.patchca.random.StrUtils;
import com.ph.base.BaseController;
import com.ph.shopping.common.core.constant.CommonConstants;
import com.ph.shopping.common.core.customenum.ResultEnum;
import com.ph.shopping.common.core.exception.BizException;
import com.ph.shopping.common.util.page.PageBean;
import com.ph.shopping.common.util.result.Result;
import com.ph.shopping.facade.merchant.entity.Position;
import com.ph.shopping.facade.merchant.service.IMerchantService;
import com.ph.shopping.facade.permission.entity.WarehouseAddress;
import com.ph.shopping.facade.permission.service.IWarehouseAddressService;
import com.ph.shopping.facade.permission.vo.SessionUserVo;
import com.ph.shopping.facade.permission.vo.WarehouseAddressVo;

/**
 * 仓库地址Controller
 * @项目：phshopping-api-platform
 *
 * @描述：
 *
 * @作者： liuy
 *
 * @创建时间：2017年3月27日
 *
 * @Copyright @2017 by liuy
 */
@Controller
@RequestMapping("api/warehouseAddress")
public class WarehouseAddressController  extends BaseController{

	//仓库地址接口
	@Reference(version="1.0.0")
	private IWarehouseAddressService iWarehouseAddressService;

	//商户接口，调用获取省市区的方法
	@Reference(version="1.0.0")
	private IMerchantService iMerchantService;
	
	/**
	 * 跳转列表页面
	 * @return
	 */
	@RequestMapping(value="/listPage",method=RequestMethod.GET)
	public String listWarehouseAddressPage(){
		return "/account/warehouseAddress/list";
	}

	/**
	 * 跳转仓库地址新增页面
	 * @return
	 */
	@RequestMapping(value="/addPage",method=RequestMethod.GET)
	public String addWarehouseAddressPage(){
		return "/account/warehouseAddress/add";
	}
	
	/**
	 * 
	 *  跳转仓库地址修改页面（根据id获取仓库地址信息）
	 * @param 
	 * @return
	 */
	@RequestMapping(value="/updatePage",method=RequestMethod.GET)
	public Object updateWarehouseAddressPage(@ModelAttribute WarehouseAddressVo warehouseAddressVo){

		ModelAndView mv=new ModelAndView("/account/warehouseAddress/update");
		try {
			WarehouseAddressVo warehouseAddressDetailVo = iWarehouseAddressService.getWarehouseAddressVoDetail(warehouseAddressVo);
			mv.addObject("warehouseAddress", warehouseAddressDetailVo);
			return mv;
		} catch (BizException e) {
			e.printStackTrace();
			mv.addObject("warehouseAddress", warehouseAddressVo);
			logger.error("获取仓库地址信息异常:", e.getMessage());
			return mv;
		}
	}
	
	/**
	 * 分页获取仓库地址列表(包括仓库地址列表和待审核仓库地址列表)
     * @param pageIndex 当前页码
     * @param pageSize 每页条数
     * @param warehouseAddressVo 查询条件
	 * @return
	 */
	@RequestMapping(value="/pagelist",method= RequestMethod.GET)
	@ResponseBody
	public Object getWarehouseAddressVoListByPage(@ModelAttribute PageBean page,@ModelAttribute WarehouseAddressVo warehouseAddressVo) throws Exception{
		
		SessionUserVo sessionUserVo = getLoginUser();	//获取session
		if(sessionUserVo!=null&&sessionUserVo.getId()!=null
				&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
			warehouseAddressVo.setUserId(sessionUserVo.getId());	//设置 查询条件，根据登录用户Id设置managerId
		}
		warehouseAddressVo.setIsable(CommonConstants.ORDER_ADDRESS_ISABLE_YES);//查询条件是否可用为：可用
		
		Result result = iWarehouseAddressService.getWarehouseAddressVoPageList(page,warehouseAddressVo);
		return result;
	}

	/**
	 * 获取仓库地址列表
     * @param warehouseAddressVo 查询条件
	 * @return
	 */
	@RequestMapping(value="/list",method=RequestMethod.GET)
	@ResponseBody
	public Object getWarehouseAddressVoList(@ModelAttribute WarehouseAddress warehouseAddress) throws Exception{

		
		SessionUserVo sessionUserVo = getLoginUser();			//获取session
		if(sessionUserVo!=null&&sessionUserVo.getId()!=null
				&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
			warehouseAddress.setUserId(sessionUserVo.getId());	//设置 查询条件，根据登录用户Id设置managerId
		}
		warehouseAddress.setIsable(CommonConstants.ORDER_ADDRESS_ISABLE_YES);//查询条件是否可用为：可用
		
		return getResult(ResultEnum.SUCCESS,iWarehouseAddressService.getWarehouseAddressVoList(warehouseAddress));
	}
	
	
	/**
	 * 新增仓库地址
	 * @param warehouseAddress
	 * @return
	 */
	@RequestMapping(value="/add",method=RequestMethod.POST)
	@ResponseBody
	public Object addWarehouseAddress(@ModelAttribute WarehouseAddress warehouseAddress, HttpServletRequest request){
		
		logger.info("仓库地址新增，传入参数：" + warehouseAddress + "" + request );
		
		SessionUserVo sessionUserVo = getLoginUser();				//获取session
		if(sessionUserVo!=null&&sessionUserVo.getId()!=null
				&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
			warehouseAddress.setCreateId(sessionUserVo.getId());	//设置创建人
			warehouseAddress.setUpdateId(sessionUserVo.getId());	//设置更新人
		}
		warehouseAddress.setUserId(sessionUserVo.getId());			//设置管理Id（商户、供应商、代理商的Id，即登录Id）
		warehouseAddress.setCreateTime(new Date());
		warehouseAddress.setUpdateTime(new Date());
		warehouseAddress.setIsable(CommonConstants.ORDER_ADDRESS_ISABLE_YES);//可用
		
		if(warehouseAddress.getAreaId()!=null&&!"".equals(warehouseAddress.getAreaId())){
			//将区域最后一级（区Id）设置为positionId
			warehouseAddress.setPositionId(Long.valueOf(warehouseAddress.getAreaId()));
			//根据positionId获取区域对象，对省市区Id进行赋值
			Position position = iMerchantService.getPositionById(warehouseAddress.getAreaId());
			if(position!=null){
				warehouseAddress.setProvinceId(position.getProvinceId());
				warehouseAddress.setCityId(position.getCityId());
				warehouseAddress.setAreaId(position.getCountyId());
			}
		}
		
		Result result = getResult(ResultEnum.SUCCESS);
		// 开始新增
		try {
			logger.debug("仓库地址新增数据：");
			logger.debug("warehouseAddress: " + warehouseAddress);
			result =this.iWarehouseAddressService.addWarehouseAddress(warehouseAddress);
		} catch (BizException e) {
			e.printStackTrace();
			logger.info("仓库地址新增失败："+e.getMessage());
			return getResult(ResultEnum.ADD_ORDER_ADDRESS_EXCEPTION);
		}
		logger.info("仓库地址新增成功");
		return result;
		
	}
	
	/**
	 * 修改仓库地址
	 * @param warehouseAddress
	 * @return
	 */
	@RequestMapping(value="/update",method=RequestMethod.POST)
	@ResponseBody
	public Object updateWarehouseAddress(@ModelAttribute WarehouseAddress warehouseAddress, HttpServletRequest request) {
		
		logger.info("仓库地址修改，传入参数：" + warehouseAddress + "" + request );

		SessionUserVo sessionUserVo = getLoginUser();			//获取session
		if(sessionUserVo!=null&&sessionUserVo.getId()!=null
				&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
			warehouseAddress.setUpdateId(sessionUserVo.getId()); //设置创建人、 更新人
		}
		warehouseAddress.setUserId(sessionUserVo.getId());		 //设置管理Id（商户、供应商、代理商的Id，即登录Id）
		warehouseAddress.setUpdateTime(new Date());

		if(warehouseAddress.getAreaId()!=null&&!"".equals(warehouseAddress.getAreaId())){
			//将区域最后一级（区Id）设置为positionId
			warehouseAddress.setPositionId(Long.valueOf(warehouseAddress.getAreaId()));
			//根据positionId获取区域对象，对省市区Id进行赋值
			Position position = iMerchantService.getPositionById(warehouseAddress.getAreaId());
			if(position!=null){
				warehouseAddress.setProvinceId(position.getProvinceId());
				warehouseAddress.setCityId(position.getCityId());
				warehouseAddress.setAreaId(position.getCountyId());
			}
		}
		
		
		// 开始修改
		try {
			logger.debug("仓库地址修改数据：");
			logger.debug("warehouseAddress: " + warehouseAddress);
			this.iWarehouseAddressService.updateWarehouseAddress(warehouseAddress);
		} catch (BizException e) {
			e.printStackTrace();
			logger.info("仓库地址修改失败："+e.getMessage());
			return getResult(ResultEnum.UPDATE_ORDER_ADDRESS_EXCEPTION);
		}
		logger.info("仓库地址修改成功");
		return getResult(ResultEnum.SUCCESS);
	}
	
	/**
	 * 设置仓库地址为默认地址
	 * @param warehouseAddress
	 * @return
	 */
	@RequestMapping(value="/updateWarehouseDefault",method=RequestMethod.POST)
	@ResponseBody
	public Object updateWarehouseDefault(@ModelAttribute WarehouseAddress warehouseAddress ){
		try {
			
			SessionUserVo sessionUserVo = getLoginUser();				//获取session
			if(sessionUserVo!=null&&sessionUserVo.getId()!=null
					&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
				warehouseAddress.setUpdateId(sessionUserVo.getId());	//设置 更新人
			}
			
			warehouseAddress.setUserId(sessionUserVo.getId());			//设置管理Id（商户、供应商、代理商的Id，即登录Id）
			warehouseAddress.setUpdateTime(new Date());					//设置 更新时间
			
			if(StrUtils.isNotEmpty(warehouseAddress.getPositionId())){
				//根据positionId获取区域对象，对省市区Id进行赋值
				Position position = iMerchantService.getPositionById(warehouseAddress.getPositionId());
				if(position!=null){
					warehouseAddress.setProvinceId(position.getProvinceId());
					warehouseAddress.setCityId(position.getCityId());
					warehouseAddress.setAreaId(position.getCountyId());
				}
			}
			
			this.iWarehouseAddressService.updateWarehouseDefault(warehouseAddress);//修改仓库地址表
			
		} catch (BizException e) {
			e.printStackTrace();
			logger.error("设置仓库地址为默认地址异常:"+ e.getMessage());
			return getResult(ResultEnum.DEFAULT_ORDER_ADDRESS_EXCEPTION);
		}
		return getResult(ResultEnum.SUCCESS);
	}
	
	/**
	 * 设置仓库地址为提货点
	 * @param warehouseAddress
	 * @return
	 */
	@RequestMapping(value="/updateWarehouseDeliveryPoint",method=RequestMethod.POST)
	@ResponseBody
	public Object updateWarehouseDeliveryPoint(@ModelAttribute WarehouseAddress warehouseAddress ){
		try {
			//获取session
			SessionUserVo sessionUserVo = getLoginUser();
			//设置 更新人
			if(sessionUserVo!=null&&sessionUserVo.getId()!=null
					&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
				warehouseAddress.setUpdateId(sessionUserVo.getId());
			}
			
			warehouseAddress.setUserId(sessionUserVo.getId());//设置管理Id（商户、供应商、代理商的Id，即登录Id）
			//设置 更新时间
			warehouseAddress.setUpdateTime(new Date());
			
			//修改仓库地址表
			this.iWarehouseAddressService.updateWarehouseDeliveryPoint(warehouseAddress);
		} catch (BizException e) {
			e.printStackTrace();
			logger.error("设置仓库地址为提货点异常:"+ e.getMessage());
			return getResult(ResultEnum.DELIVERY_POINT_ORDER_ADDRESS_EXCEPTION);
		}
		return getResult(ResultEnum.SUCCESS);
	}
	
	/**
	 * 删除
	 * @param warehouseAddress
	 * @return
	 */
	@RequestMapping(value="/delete",method=RequestMethod.POST)
	@ResponseBody
	public Object batchDeleteWarehouseAddress(String warehouseAddressIds) {
		try {
			String[] sIds = warehouseAddressIds.split(",");
			Long[] str2 = new Long[sIds.length];
	        for (int i = 0; i < sIds.length; i++) {
	            str2[i] = Long.valueOf(sIds[i]);
	        }
			List<Long> list = new ArrayList<Long>();
			Collections.addAll(list, str2);
			this.iWarehouseAddressService.batchDeleteWarehouseAddress(list);
		} catch (BizException e) { 
			e.printStackTrace();
			logger.error("删除仓库地址异常:"+ e.getMessage());
			return getResult(ResultEnum.DELETE_ORDER_ADDRESS_EXCEPTION);
		}

		return getResult(ResultEnum.SUCCESS);
	}
	
	/**
	 * 获取所有的省市县区
	 * @return
	 */
	@RequestMapping(value="/getAllPosition",method=RequestMethod.POST)
	@ResponseBody
	public  Object  getAllPosition(String pid){	
		return  iMerchantService.getAllPosition(pid);
	}
}
